//package com.wejoy.video.middle.station.data.service.file.impl;
//
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.qiniu.common.QiniuException;
//import com.qiniu.http.Response;
//import com.qiniu.storage.BucketManager;
//import com.qiniu.storage.UploadManager;
//import com.qiniu.storage.model.FetchRet;
//import com.qiniu.util.Auth;
//import com.qiniu.util.StringMap;
//import com.wejoy.video.middle.station.data.enums.dict.EnumFileResourceType;
//import com.wejoy.video.middle.station.data.enums.file.EnumUpload;
//import com.wejoy.video.middle.station.data.exception.BusinessException;
//import com.wejoy.video.middle.station.data.service.file.IFileService;
//import com.wejoy.video.middle.station.data.constant.RedisKeys;
//import com.wejoy.video.middle.station.data.util.UuidUtils;
//import com.wejoy.video.middle.station.data.util.qiniu.QiniuCustomHttpUtil;
//import com.wejoy.video.middle.station.data.vo.file.FileResLibVO;
//import com.wejoy.video.middle.station.data.vo.file.UploadFileVO;
//import org.apache.commons.lang3.StringUtils;
//import org.apache.xmlbeans.impl.util.Base64;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.cache.annotation.Cacheable;
//import org.springframework.context.annotation.Lazy;
//import org.springframework.context.annotation.Profile;
//import org.springframework.scheduling.annotation.Async;
//import org.springframework.stereotype.Component;
//import org.springframework.web.client.RestTemplate;
//
//import java.text.SimpleDateFormat;
//import java.util.Arrays;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.concurrent.LinkedBlockingQueue;
//import java.util.concurrent.ThreadPoolExecutor;
//import java.util.concurrent.TimeUnit;
//
///**
// * 开发环境使用的文件上传业务类
// *
// * @author admin on 2017/2/15.
// */
//@Profile("dev")
//@Component
//public class QiniuFileServiceImpl implements IFileService {
//    private final static Logger LOGGER = LoggerFactory.getLogger(QiniuFileServiceImpl.class);
//    // 非线程安全, 有时间改一下
//    private final static SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
//    @Value("${qiniu.image.bucket}")
//    private String imageBucket;
//    @Autowired
//    private Auth auth;
//    @Autowired
//    private UploadManager uploadManager;
//    @Autowired
//    private BucketManager bucketManager;
//    @Autowired
//    private RestTemplate restTemplate;
//    @Autowired
//    @Lazy
//    private IFileService fileService;
//    @Value("${qiniu.prefix}")
//    private String prefix;
//
//    @Override
//    public UploadFileVO upload(EnumUpload enumUpload, byte[] bytes) {
//        return uploadFileByPrefix(bytes, enumUpload);
//    }
//
//    private final static ThreadPoolExecutor IMG_THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(500, 500, 120, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new ThreadPoolExecutor.AbortPolicy());
//
//    /**
//     * 上传文件到七牛
//     *
//     * @param file       文件字节数组
//     * @param enumUpload 上传枚举
//     * @return
//     */
//    private UploadFileVO uploadFileByPrefix(byte[] file, EnumUpload enumUpload) {
//        try {
//            String date = df.format(new Date());
//            String filePath = enumUpload.getBaseDir() + "/" + date + "/" + UuidUtils.uuid() + "." + enumUpload.getSuffix();
//            Response resp = uploadManager.put(file, filePath, getUploadToken());
//            UploadFileVO result = resp.jsonToObject(UploadFileVO.class);
//            result.setKey(result.getKey());
//            result.setSuffix(enumUpload.getSuffix());
//            if (resp.isOK()) {
//                LOGGER.info("上传成功: key: {}, hash: {}", result.getKey(), result.getHash());
//                return result;
//            } else {
//                LOGGER.info("上传失败: key: {}, hash: {}", result.getKey(), result.getHash());
//                throw new BusinessException("上传文件失败");
//            }
//        } catch (QiniuException e) {
//            Response resp = e.response;
//            // 请求失败时简单状态信息
//            LOGGER.error(resp.toString());
//            LOGGER.error(e.getMessage(), e);
//            try {
//                // 响应的文本信息
//                LOGGER.error(resp.bodyString());
//            } catch (QiniuException qiniuException) {
//                LOGGER.error(qiniuException.getMessage(), qiniuException);
//            }
//        }
//        return null;
//    }
//
//    @Override
//    public String uploadFileByImgUrl(String url, String suffix) {
//        try {
//            FetchRet fetch = bucketManager.fetch(url, imageBucket, generateFileName("remoteUrl/", suffix));
//            return fetch.key;
//        } catch (QiniuException e) {
//            LOGGER.error("上传图片至七牛云时异常", e);
//        }
//        return null;
//    }
//
//
//    @Override
//    public String getUploadToken() {
//        return auth.uploadToken(imageBucket, null, 3600, new StringMap()
//                .putNotEmpty("returnBody", "{\"key\": $(key), \"hash\": $(etag), \"width\": $(imageInfo.width), \"height\": $(imageInfo.height)" +
//                        ",\"duration\": $(avinfo.format.duration), \"fileSize\": $(avinfo.format.size)}"));
//    }
//
//    @Override
//    public String getUploadToken(String filePath) {
//        StringMap returnBodyCfg = new StringMap().putNotEmpty("returnBody", "{\"key\": $(key), \"hash\": $(etag), \"width\": $(imageInfo.width), \"height\": $(imageInfo.height)" +
//                ",\"duration\": $(avinfo.format.duration), \"fileSize\": $(avinfo.format.size)}");
//        // mp4进行转码处理
//        if (filePath.contains(".mp4")) {
//            returnBodyCfg.putNotEmpty("persistentOps", "avthumb/mp4|saveas/" + new String(Base64.encode((imageBucket + ":" + filePath).getBytes())));
//        }
//        return auth.uploadToken(imageBucket, null, 3600, returnBodyCfg);
//    }
//
//    private static String generateFileName(String prefix, String suffix) {
//        return String.format("%s%s/%s%s", prefix == null ? "" : prefix, df.format(new Date()), UuidUtils.uuid(), suffix == null ? "" : suffix);
//    }
//
//    @Cacheable(value = RedisKeys.QINIU_VIDEO_INFO_LIST, key = "#videoPath")
//    @Override
//    public FileResLibVO getVideoByVideoPath(String videoPath) {
//        if (StringUtils.isEmpty(videoPath)) {
//            return null;
//        }
//        JSONObject result = null;
//        try {
//            result = restTemplate.getForObject(prefix + "/" + videoPath + "?avinfo", JSONObject.class);
//        } catch (Exception e) {
//            LOGGER.error("未找到对应路径文件!", e.getMessage());
//            return null;
//        }
//        if (result == null) {
//            return null;
//        }
//        JSONArray streams = result.getJSONArray("streams");
//        JSONObject videoInfoObject = streams.getJSONObject(0);
//        Integer width = videoInfoObject.getInteger("width");
//        Integer height = videoInfoObject.getInteger("height");
//
//        JSONObject format = result.getJSONObject("format");
//        FileResLibVO fileResLibVO = new FileResLibVO();
//        String suffix = "";
//        try {
//            suffix = videoPath.substring(videoPath.lastIndexOf(".")).toLowerCase();
//        } catch (Exception e) {
//            suffix = "";
//        }
//        fileResLibVO.setImgWidth(width);
//        fileResLibVO.setImgHeight(height);
//        fileResLibVO.setFileSize(format.getLong("size"));
//        fileResLibVO.setPath(videoPath);
//        fileResLibVO.setType(EnumFileResourceType.VIDEO.getCode());
//        fileResLibVO.setDuration(format.getDouble("duration"));
//        return fileResLibVO;
//    }
//
//
//    @Override
//    @Async
//    public void refreshCDN(String path) {
//        if (StringUtils.isEmpty(path)) {
//            return;
//        }
//        Map<String, Object> body = new HashMap<>(1);
//        body.put("urls", Arrays.asList(path));
//        JSONObject result = QiniuCustomHttpUtil.post("http://fusion.qiniuapi.com/v2/tune/refresh", JSON.toJSONString(body));
//        LOGGER.info("path={},刷新CDN结果={}", path, JSONObject.toJSONString(result));
//    }
//
//    @Cacheable(value = RedisKeys.QINIU_IMAGE_INFO_LIST, key = "#imagePath")
//    @Override
//    public FileResLibVO getImageByImagePath(String imagePath) {
//        if (StringUtils.isEmpty(imagePath)) {
//            return null;
//        }
//        JSONObject result = null;
//        try {
//            result = restTemplate.getForObject(prefix + "/" + imagePath + "?imageInfo", JSONObject.class);
//        } catch (Exception e) {
//            LOGGER.error("未找到对应路径文件!", e.getMessage());
//            return null;
//        }
//        if (result == null) {
//            return null;
//        }
//        FileResLibVO fileResLibVO = new FileResLibVO();
//        fileResLibVO.setPath(imagePath);
//        fileResLibVO.setType(EnumFileResourceType.IMG.getCode());
//        fileResLibVO.setImgHeight(result.getInteger("height"));
//        fileResLibVO.setImgWidth(result.getInteger("width"));
//        fileResLibVO.setFileSize(result.getLong("size"));
//        return fileResLibVO;
//    }
//}
